package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"sync"

	"gitee.com/hlwqds/clientSimulation/src/lib/lg"
	queryid "gitee.com/hlwqds/clientSimulation/src/moudles/queryId"
	"github.com/BurntSushi/toml"
	"github.com/go-redis/redis"
	"github.com/judwhite/go-svc/svc"
	"github.com/mreiferson/go-options"
)

var ctx = context.Background()

type program struct {
	once    sync.Once
	rdb     *redis.Client
	logger  lg.Logger
	logfile *os.File
	server  http.Server
	options *queryid.Options
}

func (p *program) Init(env svc.Environment) error {
	var err error
	opts := queryid.NewOptions()
	flagSet := queryIDFlagSet(opts)
	flagSet.Parse(os.Args[1:])

	var cfg config
	configFile := flagSet.Lookup("config").Value.String()
	if configFile != "" {
		_, err = toml.DecodeFile(configFile, &cfg)
		if err != nil {
			goto _error
		}
	}
	options.Resolve(opts, flagSet, cfg)
	p.options = opts
_error:
	return err
}

func (p *program) Start() error {
	p.rdb = redis.NewClient(&redis.Options{
		Addr:     p.options.RedisAddress,
		Password: p.options.RedisPassword,
		DB:       0,
	})

	pong, _ := p.rdb.Ping().Result()
	fmt.Println(pong)

	logPath := p.options.LogPath + "/test.log"

	logfile, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		return err
	}
	p.logger = log.New(logfile, "[QueryId]", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
	p.logfile = logfile
	reqD := queryid.ReqPriD{
		Rdb:      p.rdb,
		Logger:   p.logger,
		LogLevel: queryid.LOG_DEBUG,
	}

	p.server = http.Server{
		Addr: p.options.HTTPAddress,
	}
	http.HandleFunc("/ivr/queryid", reqD.HandleAPIReuqest)
	http.HandleFunc("/CallPush", reqD.HandleCallPushAPIReuqest)

	p.server.ListenAndServe()
	return nil
}

func (p *program) Stop() error {
	p.rdb.Close()
	p.server.Close()
	p.logfile.Close()
	return nil
}
